<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class GoodsComment extends Model
{

    

    

    // 表名
    protected $name = 'goods_comment';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];
	
    public function user() {
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 订单评价
	 * @param string $orderId
	 * @param $comment
	 * @param $userId
	 * @return bool|Model
	 * @throws \think\exception\PDOException
	 */
	public function comment($orderId, $comment, $userId) {
		$this->startTrans();
		try {
			$order = Db::name('order')
				->where(['id' => $orderId, 'user_id' => $userId])
				->find();
			if(!$order) {
				throw new Exception('订单不存在');
			}
			
			if($order['status'] != Order::STATUS_SUCCESS || $order['comment_status'] != 0) {
				throw new Exception('非待评价订单');
			}
			
			$orderRes = Db::name('order')
				->where(['id' => $orderId])
				->update(['comment_status' => 1, 'update_time' => time()]);
			
			if(!$orderRes) {
				throw new Exception('更改订单评价状态出错');
			}
			
			foreach ($comment as $item) {
				$res = Db::name('goodsComment')
					->insert([
						'user_id' => $userId,
						'order_id' => $orderId,
						'goods_id' => $item['goods_id'],
						'score' => $item['score'],
						'images' => $item['images'],
						'content' => $item['content'],
						'create_time' => time(),
						'update_time' => time()
					]);
				if(!$res) {
					throw new Exception('添加评价出错');
				}
			}
			
			$this->commit();
			return true;
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	
	}





}
